package com.jiuyou.clientController.mall.order;

import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.kuaidi.SignUtils;
import com.ruoyi.common.utils.kuaidi.core.*;
import com.ruoyi.shopping.domain.MallOrder;
import com.ruoyi.shopping.service.IMallOrderService;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author chengliang
 * @date 2022/8/16
 **/
@RestController
@RequestMapping("/client/logistics")
public class LogisticsQuery extends BaseClient {
    @Autowired
    private IMallOrderService orderService;

    @Autowired
    private ISysConfigService configService;
    @RequestMapping("/query/{id}")
    public AjaxResult query(@PathVariable Long id) throws Exception {
        MallOrder mallOrder = orderService.selectMallOrderById(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("success",false);
        QueryTrackReq queryTrackReq = new QueryTrackReq();
        String ks = configService.selectConfigByKey("kd_customer");
        String kk = configService.selectConfigByKey("kd_key");

        queryTrackReq.setCustomer(ks);
        JSONObject jso = new JSONObject();
        jso.put("com",mallOrder.getCourierCompany());
        jso.put("num",mallOrder.getCourierNumber());
        queryTrackReq.setParam(jso.toJSONString());
        queryTrackReq.setSign(SignUtils.querySign(jso.toJSONString(),kk,queryTrackReq.getCustomer()));
        QueryTrackResp resp = this.queryTrack(queryTrackReq);

        if("ok".equals(resp.getMessage())){
            ArrayList<JSONObject> os = new ArrayList<>();
            resp.getData().forEach(e->{
                JSONObject res = new JSONObject();
                res.put("time",e.getFtime());
                res.put("context",e.getContext());
                os.add(res);
            });
            map.put("list",os);
            map.put("status",resp.getIscheck());
            map.put("success",true);

        }
        return AjaxResult.success(map);
    }
    public String getApiUrl(BaseRequest request) {
        return ApiInfoConstant.QUERY_URL;
    }

    private QueryTrackResp queryTrack(QueryTrackReq queryTrackReq) throws Exception{
        HttpResult httpResult = execute(queryTrackReq);
        if (httpResult.getStatus() == HttpStatus.SC_OK && StringUtils.isNotBlank(httpResult.getBody())){
            return new Gson().fromJson(httpResult.getBody(),QueryTrackResp.class);
        }
        return null;
    }

}
